<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Helpers\Enums\ResponseEnum;
use App\Http\Controllers\BaseController;
use App\Http\Requests\User\LoginRequest;
use App\Http\Requests\User\RegisterRequest;
use App\Http\Resources\Api\UserResource;
use App\Models\User\User;
use App\Services\User\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    /**
     * 用户注册
     * @throws BusinessException
     */
    public function register(RegisterRequest $registerRequest): JsonResponse
    {
        $params = $registerRequest->all('mobile', 'password', 'code');
        // 存储用户信息
        UserService::getInstance()->store($params);
        return $this->success(null, ResponseEnum::USER_SERVICE_REGISTER_SUCCESS);
    }

    /**
     * 用户登录
     * @param LoginRequest $loginRequest
     * @return JsonResponse
     */
    public function login(LoginRequest $loginRequest): JsonResponse
    {
        $params = $loginRequest->all(['mobile', 'password']);
        if (!$token = auth('api')->attempt($params)) {
            return $this->fail(ResponseEnum::SERVICE_LOGIN_ACCOUNT_ERROR);
        }
        // 记录用户登录日志
        $this->createActivityLog('user_login', $params, ResponseEnum::USER_SERVICE_LOGIN_SUCCESS[1]);
        // 返回用户信息
        $user = [];
        $user['user_info'] = auth('api')->user();
        $user['user_token'] = $this->respondWithToken($token);
        return $this->success($user, ResponseEnum::USER_SERVICE_LOGIN_SUCCESS);
    }

    /**
     * 登录信息
     * @return JsonResponse
     */
    public function me(): JsonResponse
    {
        return $this->success(new UserResource(auth('api')->user()));
    }

    /**
     * 退出登录
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        auth('api')->logout();
        return $this->success(null, ResponseEnum::USER_SERVICE_LOGOUT_SUCCESS);
    }


    /**
     * 用户信息
     * @param Request $request
     * @return JsonResponse
     */
    public function show(Request $request): JsonResponse
    {
        $userId =  $request->get('user_id');
        return $this->success(new UserResource(User::find($userId)));
    }

}
